package com.tencent.youtufacetrack;

import android.text.TextUtils;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by rincliu on 2015/12/29.
 */
public class HttpUtil {

    private static final int DEFAULT_TIMEOUT_MILLIS = 10 * 1000;

    private static final String CHARSET_UTF8 = "UTF-8";

    public interface HttpResponseListener{
        void onSuccess(String responseStr);
        void onFail(int statusCode);
    }

    /**
     *
     * @param url
     * @param str
     * @return
     * @throws IOException
     */
    public static String post(String url, String str, HttpResponseListener listener) throws IOException {
        HttpURLConnection conn = buildConnection(url, DEFAULT_TIMEOUT_MILLIS);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        if (!TextUtils.isEmpty(str)) {
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, CHARSET_UTF8));
            writer.write(str);
            writer.flush();
            writer.close();
            os.close();
        }
        return getResponse(conn, listener);
    }

    private static HttpURLConnection buildConnection(String url, int timeoutMillis) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(timeoutMillis);
        conn.setReadTimeout(timeoutMillis);
        return conn;
    }

    private static String getResponse(HttpURLConnection conn, HttpResponseListener listener) throws IOException {
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream is = conn.getInputStream();
            StringBuilder buf = new StringBuilder();
            byte[] buffer = new byte[1024];
            int x;
            while ((x = is.read(buffer)) != -1) {
                buf.append(new String(buffer, 0, x));
            }
            is.close();
            String str = buf.toString();
            if(listener != null){
                listener.onSuccess(str);
            }
            return str;
        } else{
            if(listener != null){
                listener.onFail(responseCode);
            }
            return null;
        }
    }
}
